package sc.common.test.hopper.handler;

import org.jboss.netty.buffer.ChannelBuffer;
import org.jboss.netty.channel.Channel;
import org.jboss.netty.channel.ChannelHandlerContext;
import org.jboss.netty.handler.codec.replay.ReplayingDecoder;

import sc.common.test.hopper.enums.MyMessageDecoderState;
import sc.common.test.hopper.enums.Verb;
import sc.common.test.hopper.model.MyMessage;

public class MyMessageDecoder extends ReplayingDecoder<MyMessageDecoderState> {

	int size;

	public MyMessageDecoder() {
		super(MyMessageDecoderState.READ_SIZE);
	}

	@Override
	protected Object decode(ChannelHandlerContext ctx, Channel channel,
			ChannelBuffer buffer, MyMessageDecoderState state) throws Exception {
		switch (state) {
		case READ_SIZE:
			size = buffer.readInt();
			checkpoint(MyMessageDecoderState.READ_CONTENT);
			break;
		case READ_CONTENT:
			if (buffer.readableBytes() < size)
				return null;
			MyMessage message = MyMessage.new4receive();
			message.setId(buffer.readInt());
			message.setVerb(Verb.getByType(buffer.readInt()));
			checkpoint(MyMessageDecoderState.READ_SIZE);
			return message;
		}
		return null;
	}
}
